package ci.web.codec;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.codec.http.multipart.FileUpload;

/**
 * http上次的文件
 * @author zhh
 */
public class FileItem {

    private FileUpload fu;
    private File tmp;
    public FileItem(FileUpload fu){
        this.fu = fu;
    }
    /**
     * 上传时form中file的文件名
     * @return
     */
    public String getName(){
        return fu.getName();
    }
    /**
     * 上传时form中标记的文件类型
     * @return
     */
    public String getContentType(){
        return fu.getContentType();
    }
    /**
     * 上传的临时文件
     * @return
     */
    public File getFile(){
        if(tmp==null){
            try {
                if(fu instanceof DiskFileUpload){
                    DiskFileUpload dfu = (DiskFileUpload)fu;
                    tmp = dfu.getFile();
                }else{
                    tmp = tempFile(false, DiskFileUpload.prefix, DiskFileUpload.baseDirectory, fu.getFilename());
                    Files.write(tmp.toPath(), fu.get());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tmp;
    }
    /**
     * 删除临时文件
     */
    public void delete(){
        if(tmp!=null){
            tmp.delete();
        }else{
            fu.delete();
        }
    }
    
    private static File tempFile(boolean deleteOnExit, String preFix, String tmpDir, String suffix) throws IOException {
        File tmpFile;
        if (tmpDir==null) {
            // create a temporary file
            tmpFile = File.createTempFile(preFix, suffix);
        } else {
            tmpFile = File.createTempFile(preFix, suffix, new File(
                    tmpDir));
        }
        if (deleteOnExit) {
            tmpFile.deleteOnExit();
        }
        return tmpFile;
    }
}
